package club.emergency.wechat.question.operate.provider.aop;

import club.emergency.wechat.common.response.ResponseEntity;
import club.emergency.wechat.common.utils.JsonConvert;
import club.emergency.wechat.model.question.QuestionDailyRecord;
import club.emergency.wechat.persistence.question.QuestionDailyRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Create with IntelliJ IDEA
 * Project Name: wechat
 * Package Name: club.emergency.wechat.question.operate.provider.aop
 * Date: 2019/3/28
 *
 * @author: 快乐的小菌菌
 * Description:
 */
@Slf4j
@Aspect
@Component
public class QuestionInformationCollectionAop {

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    private QuestionDailyRecordMapper questionDailyRecordMapper;

    private PlatformTransactionManager platformTransactionManager;

    public QuestionInformationCollectionAop(QuestionDailyRecordMapper questionDailyRecordMapper, PlatformTransactionManager platformTransactionManager) {
        this.questionDailyRecordMapper = questionDailyRecordMapper;
        this.platformTransactionManager = platformTransactionManager;
    }

    @Pointcut("execution(String club.emergency.wechat.question.operate.provider.impl.QuestionOperateImpl.checkCorrectForDaily(..))")
    public void checkCorrectPointCut() {
    }

    /**
     * 记录题目被答次数
     */
    @AfterReturning(value = "checkCorrectPointCut()", returning = "result")
    public void saveAnswerQuestionRecords(JoinPoint joinPoint, Object result) {
        String res = (String) result;
        ResponseEntity responseEntity = new JsonConvert<ResponseEntity>().jsonDecode(res, ResponseEntity.class);
        String userOption = (String) joinPoint.getArgs()[1];
        QuestionDailyRecord questionDailyRecord = (QuestionDailyRecord) joinPoint.getArgs()[0];
        questionDailyRecord.setIsRight((Integer) responseEntity.getData());
        questionDailyRecord.setUserOption(userOption);
        TransactionStatus transaction = platformTransactionManager.getTransaction(new DefaultTransactionDefinition());
        executorService.submit(() -> {
            try {
                questionDailyRecordMapper.insert(questionDailyRecord);
            } catch (Exception e) {
                platformTransactionManager.rollback(transaction);
            }
        });
    }

}
